package com.vdg.fps.ulti;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.facebook.HttpMethod;
import com.vdg.fps.data.AccountProxy;
import com.vdg.fps.data.FaceBookAccount;
import com.vdg.fps.listener.OnHttpResponse;

import android.content.Context;
import android.net.Proxy;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class FaceBookHTTPRequest {
	private enum RESPONSE_TYPE {
		LOCATION_HEADER, RESPONSE
	}

	private static class HttpRequestAsyncTask extends
			AsyncTask<String, String, String> {
		private FaceBookAccount mFaceBookAccount;
		private ArrayList<BasicNameValuePair> mListParams;
		private ArrayList<BasicNameValuePair> mListHeaders;
		private HttpMethod mHttpMethod;
		private OnHttpResponse mOnHttpResponse;
		private RESPONSE_TYPE mResponseType;
		private boolean mIsRedirect;

		public HttpRequestAsyncTask(ArrayList<BasicNameValuePair> listParams,
				ArrayList<BasicNameValuePair> listHeaders,
				FaceBookAccount facebookAccount, HttpMethod method,
				RESPONSE_TYPE responseType, OnHttpResponse onHttpResponse,
				boolean isRedirect) {
			this.mOnHttpResponse = onHttpResponse;
			mFaceBookAccount = facebookAccount;
			mListParams = listParams;
			this.mResponseType = responseType;
			this.mListHeaders = listHeaders;
			this.mIsRedirect = isRedirect;
			mHttpMethod = method;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			mOnHttpResponse.onResponse(result);
			super.onPostExecute(result);
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			HttpResponse response = null;
			// HttpPost httpPost = new HttpPost(params[0]);

			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				if (mFaceBookAccount.getProxy() != null) {
					setProxy(httpClient, mFaceBookAccount.getProxy());
				}
				if (mHttpMethod == HttpMethod.GET) {
					HttpClientParams.setRedirecting(httpClient.getParams(),
							mIsRedirect);
					HttpGet httpGet = new HttpGet(params[0]);
					if (mListHeaders != null && mListHeaders.size() > 0) {
						for (BasicNameValuePair header : mListHeaders) {
							httpGet.addHeader(header.getName(),
									header.getValue());
						}
					}
					// if (mListParams != null && mListParams.size() > 0) {
					// httpGet.setEntity(new UrlEncodedFormEntity(
					// mListParams));
					// }
					if (mFaceBookAccount.getCookies() != null
							&& mFaceBookAccount.getCookies().getCookieString() != null
							&& !mFaceBookAccount.getCookies().getCookieString()
									.equals("")) {
						httpGet.addHeader("Cookie", mFaceBookAccount
								.getCookies().getCookieString());
					}
					response = httpClient.execute(httpGet);
					for (Header header : response.getAllHeaders()) {
						Log.v("debug", "header111 = " + header.getName()
								+ "   value = " + header.getValue());
					}
					if (mResponseType == RESPONSE_TYPE.LOCATION_HEADER) {
						if (response != null
								&& response.getLastHeader("Location") != null)
							return response.getLastHeader("Location")
									.getValue();
					}
				} else {
					if (mHttpMethod == HttpMethod.POST) {
						HttpClientParams.setRedirecting(httpClient.getParams(),
								mIsRedirect);
						HttpPost httpPost = new HttpPost(params[0]);
						if (mListHeaders != null && mListHeaders.size() > 0) {
							for (BasicNameValuePair header : mListHeaders) {
								httpPost.addHeader(header.getName(),
										header.getValue());
							}
						}
						if (mFaceBookAccount.getCookies().getCookieString() != null
								&& !mFaceBookAccount.getCookies()
										.getCookieString().equals("")) {
							httpPost.addHeader("Cookie", mFaceBookAccount
									.getCookies().getCookieString());
						}

						if (mListParams != null && mListParams.size() > 0) {
							httpPost.setEntity(new UrlEncodedFormEntity(
									mListParams, "UTF-8"));
						}
						//
						response = httpClient.execute(httpPost);
						for (Header header : response.getAllHeaders()) {
							Log.v("debug", "header222 = " + header.getName()
									+ "   value = " + header.getValue());
						}
						if (mResponseType == RESPONSE_TYPE.LOCATION_HEADER) {
							if (response != null
									&& response.getLastHeader("Location") != null)
								return response.getLastHeader("Location")
										.getValue();
						}
						// Log.v("debug","response22 = "+EntityUtils.toString(response.getEntity()));
						// if (mResponseType == RESPONSE_TYPE.LOCATION_HEADER) {
						// return response.getLastHeader("Location")
						// .getValue();
						// }
					}
				}
				// create a list to store HTTP variables and their values
				// if (mListParams != null && mListParams.size() > 0) {
				// httpPost.setEntity(new UrlEncodedFormEntity(mListParams));
				// }
				// send the variable and value, in other words post, to the URL
				// File sdCard = Environment.getExternalStorageDirectory();
				String result = EntityUtils.toString(response.getEntity());
				// File file = new File(sdCard, "test.html");
				//
				// if (!file.exists()) {
				// file.createNewFile();
				// }
				//
				// FileWriter fileWriter = new FileWriter(Environment
				// .getExternalStorageDirectory().getPath()
				// + "/test1.html");
				//
				// fileWriter.write(result);
				// fileWriter.flush();
				//
				// fileWriter.close();
				Log.v("debug", " result = " + result);
				return result;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	public static void setProxy(DefaultHttpClient httpclient,
			AccountProxy accproxy) {
		final String PROXY_IP = accproxy.getProxyHost();
		final int PROXY_PORT = Integer.parseInt(accproxy.getProxyPort());
		if (accproxy.getUserName() == null || accproxy.getUserName().equals("")) {
			httpclient.getCredentialsProvider().setCredentials(
					new AuthScope(PROXY_IP, PROXY_PORT), null);
		} else {
			httpclient.getCredentialsProvider().setCredentials(
					new AuthScope(PROXY_IP, PROXY_PORT),
					new UsernamePasswordCredentials(accproxy.getUserName(),
							accproxy.getPassword()));
		}

		HttpHost proxy = new HttpHost(PROXY_IP, PROXY_PORT);

		httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
				proxy);

	}

	public static void getRequestHeader(String url, HttpMethod httpMethod,
			ArrayList<BasicNameValuePair> listParams, FaceBookAccount account,
			ArrayList<BasicNameValuePair> listHeaders,
			OnHttpResponse onHttpResponse, boolean isRedirect) {
		(new HttpRequestAsyncTask(listParams, listHeaders, account, httpMethod,
				RESPONSE_TYPE.LOCATION_HEADER, onHttpResponse, isRedirect))
				.execute(url);
	}

	public static void getRequestText(String url, HttpMethod httpMethod,
			ArrayList<BasicNameValuePair> listParams, FaceBookAccount account,
			ArrayList<BasicNameValuePair> listHeaders,
			OnHttpResponse onHttpResponse, boolean isRedirect) {
		(new HttpRequestAsyncTask(listParams, listHeaders, account, httpMethod,
				RESPONSE_TYPE.RESPONSE, onHttpResponse, isRedirect))
				.execute(url);
	}
}
